/*
* @Author: zhangsai
* @Date: 2018/1/17
* @Last Modified by: zhangsai
* @Last Modified time: 2018/1/17
* @description: 上传按钮
*/
<template>
    <div>
        <el-button type="primary" size="medium" @click="dialogVisible = true" :disabled="disabled">上传</el-button>
        <!--上传框-->
        <el-dialog :title="title" :visible.sync="dialogVisible" width="500px" @close="closeDialog" append-to-body :close-on-click-modal="false">
            <div>
                <el-form ref="form" label-width="80px">
                    <el-form-item label="文档分类:" v-if="isShowFileChildType">
                        <el-select v-model="fileChildType">
                            <el-option  v-for="(type, index) in fileChildTypeList"
                                        :key="index"
                                        :value="type.id"
                                        :label="type.cnName">
                            </el-option>
                        </el-select>
                        <div class="ca-inline-block ca-m-l-20">
                            <csEditFileName :fileType="fileType"
                                            @uploadFileChildType="uploadFileChildType">
                            </csEditFileName>
                        </div>
                    </el-form-item>
                    <el-form-item label="文档选择:">
                        <el-upload
                            :limit="limit"
                            class="upload-demo"
                            ref="upload"
                            :multiple="multiple"
                            :data="uploadData"
                            :action="action"
                            :headers="headers"
                            :before-upload="beforeUpload"
                            :on-success="handleSuccess"
                            :on-remove="remove"
                            :auto-upload="false"
                            :on-exceed="handleExceed"
                            :on-change="fileChange">
                            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                            <div slot="tip" class="el-upload__tip">{{uploadTip}}</div>
                        </el-upload>
                    </el-form-item>
                </el-form>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeDialog">取 消</el-button>
                <el-button type="primary" @click="submitUpload">上传</el-button>
            </div>
        </el-dialog>
        <!--上传框 end-->
    </div>
</template>

<script type="text/ecmascript-6">
    import { api } from './api';
    import { STATUS_HTTP_SUCCESS, apiHttp } from '__service/csHttp';
    export default {
        data() {
            return {
                dialogVisible: false,
                // 已上传文件列表
                fileList: [],
                // 上传需要的额外参数
                uploadData: {},
                // 设置token
                headers: { 'X-Token': this.$store.state.user.token	},
                // 上传地址
                action: this.baseURL + api.UPLOAD_FILE.url,
                // 文件夹
                fileChildType: '',
                // 文件夹列表
                fileChildTypeList: [],
                // 修改文件名称 弹框
                dialogFileNameVisible: false,
                // 支持的文件格式集合
                typeList: this.$store.state.csConst.FILE_TYPE,
                // 多选后上传成功后的返回值的集合
                multipleUploadSuccessRes: [],
            }
        },
        watch: {
            fileType: function (val) {
                this.fileType = val;
                this.action = this.baseURL + api.UPLOAD_FILE.url + `?industryId=${this.industryId}&businessId=${this.businessId}&fileType=${this.fileType}&fileChildType=${this.fileChildType}`;
            },
            'fileChildType': function (newOld) {
                this.action = this.baseURL + api.UPLOAD_FILE.url + `?industryId=${this.industryId}&businessId=${this.businessId}&fileType=${this.fileType}&fileChildType=${newOld}`;
            }
        },
        props: {
            multiple: {
                type: Boolean,
                default: function () {
                    return true
                }
            },
            limit: {
                type: Number,
                default: function () {
                    return
                }
            },
            title: {
                type: String,
                default() {
                    return '文档上传';
                }
            },
            // 文件类型
            fileType: {
                type: String,
                default() {
                    return '';
                }
            },
            // 业务id
            businessId: {
                type: String,
                default() {
                    return '';
                }
            },
            // 行业id
            industryId: {
                type: String,
                default() {
                    return '';
                }
            },
            // 是否显示 FileChildType
            isShowFileChildType: {
                type: Boolean,
                default() {
                    return false;
                }
            },
            // 上传提示  只能上传ppt
            uploadTip: {
                type: String,
                default() {
                    return '';
                }
            },
            // 上传类型 all  全部格式 详见 csConst   自选 'txt,jpg,ppt'
            uploadType: {
                type: String,
                default() {
                    return 'all';
                }
            },
            //文件成功返回的数据
            getFileUploadedReturnData: { //一个参数arr，文件上传成功返回的id
                type: Function,
                default: function () {}
            },
            //删除文件的id
            deleteFileId: {
                type: Function,
                default: function () {}
            },
            disabled: {
                type: Boolean,
                default() {
                    return false;
                }
            }

        },
        mounted() {
            this.action = this.action + `?industryId=${this.industryId}&businessId=${this.businessId}&fileType=${this.fileType}&fileChildType=${this.fileChildType}`;
            this.getFileChildType();
        },
        methods: {
            // 达到上传最大个数
            handleExceed(files) {
                this.fileList[0].name = files[0].name
                this.fileList[0].size = files[0].size
                this.fileList[0].raw = files[0]
                this.fileList[0].raw.uid = this.fileList[0].uid
            },
            fileChange(file) {//本次上传的列表
                if (file.status === 'ready') {//如果文件上传成功，加入到显示列表中
                    this.fileList.push(file)
                }
            },
            //文件成功返回的数据
            getFileUploadedReturnDataFun(fileList) { //数据处理 只返回id
                let arr = [];
                fileList.map((item)=>{
                    arr.push(item.response.data)
                })
                this.getFileUploadedReturnData(arr)
            },
            remove(file, fileList) {
                this.fileList = [].concat(fileList);
            },
            // 上传之前
            beforeUpload(file) {
                let isLt20M = file.size / 1024 / 1024 < 20;
                let isType = false;
                let name = file.name.split('.');
                let type = name[name.length - 1].toLowerCase();
                // 默认支持格式
                if (this.uploadType === 'all') {
                    isType = this.typeList.indexOf(type) !== -1;
                } else { // 传参数支持格式
                    isType = this.uploadType.split(',').indexOf(type) !== -1;
                }
                // 超过20M
                if (!isLt20M) {
                    this.$message.error('上传文件大小不能超过 20MB!');
                    return false;
                }
                if (!isType) {
                    this.$message.error('不支持的文件类型');
                    return false;
                }
                //console.log(this.action, '{{this.action}}>>>>')
                return isLt20M && isType;
            },
            // 点击上传按钮
            submitUpload() {
                if (!this.fileChildType && this.isShowFileChildType) {
                    this.$message.error('请选择文档分类');
                    return;
                }
                if (this.fileList.length === 0) {
                    this.$message.error('请选取文件');
                    return;
                }
                this.$refs.upload.submit();
            },
            // 上传成功
            handleSuccess(response, file, fileList) {
                    if (response.resCode === STATUS_HTTP_SUCCESS) {
                        this.multipleUploadSuccessRes.push(response);
                        // 上传多个时,判断是否全部成功后才返回
                        if (this.multipleUploadSuccessRes.length === fileList.length) {
                            this.$refs.upload.clearFiles();
                            this.getFileUploadedReturnDataFun(fileList);
                            this.dialogVisible = false;
                            this.$message.success('上传成功');
                            this.$emit('getFileList');
                            this.multipleUploadSuccessRes = [];
                        }
                    } else {
                            this.$message.error(response.resMsg);
                            this.dialogVisible = false;
                            this.$emit('getFileList');
                            this.multipleUploadSuccessRes = [];
                    }
            },
            // 获取文件夹列表
            async getFileChildType() {
                let params = {
                    parentType: this.fileType
                };
                let resData = await apiHttp(api.GET_FILE_CHILD_LIST, params);
                if (resData.resCode === STATUS_HTTP_SUCCESS) {
                    this.fileChildTypeList = resData.data || [];
                }
            },
            //
            uploadFileChildType() {
                this.getFileChildType();
                this.fileChildType = '';
            },
            //关闭
            closeDialog() {
                this.$refs.upload.uploadFiles = []  //取消时清空数组
                this.dialogVisible = false;
                this.$emit('getFileList');
            }
        },
        components: {
            'csEditFileName': require('./editFileName.vue'),
        },
    }
</script>
<style rel="stylesheet/scss" lang="scss" scoped>

</style>
